package com.ctg.itrdc.imageconsole.service.impl;


import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.ctg.itrdc.imageconsole.common.util.ZooKeeperOperator;
import com.ctg.itrdc.imageconsole.service.ICommonService;
import com.ctg.itrdc.imageconsole.service.IZkService;


/**
 * 
 * @Description 
 * @author <a href="mailto:18070514058@163.com">Piao.Wu</a>
 * @Data 2016年5月6日
 * @Version 1.0.0
 */
@Component("zkService")
public class ZkServiceImpl implements IZkService {
	private static Logger logger = Logger.getLogger(ZkServiceImpl.class);
	@Resource
	private ICommonService commonService;
	protected static ZooKeeperOperator zkoperator = new ZooKeeperOperator();
	public static String hostIp = null;

	@Override
	public void registerHostIpToZk() {
		ZooKeeperOperator zkoperator = new ZooKeeperOperator();
		if (hostIp==null) {
			hostIp = commonService.getHostIp();
		}
		String nodePath = commonService.getProperties("common").getProperty("zookeeper.index.path")
				+"/"+hostIp;
		logger.info("节点路径(nodePath):"+nodePath);
		try {
			String ip = commonService.getProperties("common").getProperty("zookeeper.host");
			String port = commonService.getProperties("common").getProperty("zookeeper.port");
			zkoperator.connect(ip+":"+port);
			// 每次创建之前先判断该节点是否已经存在
			if(!zkoperator.getChild(nodePath)){
				zkoperator.createChildNode(nodePath, "".getBytes());
			}else {
				logger.info("节点已经存在，不再创建。");
			}
		} catch (Exception e) {
			logger.error("本机ip注册到zk时发生异常", e);
		} 
	}

	@Override
	public boolean checkFirstZkNode() {
		if (hostIp==null) {
			hostIp = commonService.getHostIp();
		}
		String nodePath = commonService.getProperties("common").getProperty("zookeeper.index.path");
		try {
			String zkip = commonService.getProperties("common").getProperty("zookeeper.host");
			String zkport = commonService.getProperties("common").getProperty("zookeeper.port");
			zkoperator.connect(zkip+":"+zkport);
			List<String> nodes = zkoperator.getNode(nodePath);
			if(nodes==null||nodes.size()==0||!nodes.contains(hostIp)){
				// 如果在该路径下没有发现本机ip，则重新注册一次
				registerHostIpToZk();
				logger.warn("在该路径下没有发现本机ip，则重新注册一次");
				return true;
			}
			logger.info("zk路径("+nodePath+")下的第一个节点ip:"+nodes.get(0));
			logger.info("本机ip:"+hostIp);
			if (nodes.get(0).equals(hostIp)) {
				return true;
			}else {
				return false;
			}
		} catch (Exception e) {
			logger.error("本机ip与路径("+nodePath+")下的第一个节点对比时发生异常", e);
			return false;
		} finally{
			try {
				zkoperator.close();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main( String[] args ){
	}
}
